﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Threading;
using System.Collections.ObjectModel;

namespace MTGScore
{
    public class SavedMatches
    {
        public List<SavedMatch> matches;
        public SavedMatches()
        {
            matches = new List<SavedMatch>();
        }
    }

    public static class History
    {
        //static string list_path = "SavedHistoriesList.txt";
        public static void CreateHistory(ListBox list, SavedMatch match)
        {
            list.Items.Clear();
            if (match == null)
                return;
            for (int i = 0; i < match.savedMoments.Count; i++)
            {
                var m = match.savedMoments[i];

                list.Items.Add(new TextBlock() { Text = "" + m.player1_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Width = 70 });
                list.Items.Add(new TextBlock() { Text = "" + m.player1_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(75, -27, 0, 0), Width = 70 });
                list.Items.Add(new TextBlock() { Text = "" + m.player2_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(150, -27, 0, 0), Width = 70 });
                list.Items.Add(new TextBlock() { Text = "" + m.player2_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(225, -27, 0, 0), Width = 70 });
                list.Items.Add(new TextBlock() { Text = "" + m.time_span, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(320, -27, 0, 0), Width = 140 });


                //list.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player1_life, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25, 0, 0, 0), Width = 70 });
                //list.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player1_center, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+75, -27, 0, 0), Width = 70 });
                //list.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player2_life, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+150, -27, 0, 0), Width = 70 });
                //list.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player2_center, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+225, -27, 0, 0), Width = 70 });
                //list.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.time_span, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+320, -27, 0, 0), Width = 140 });

                //list.Items.Add("" + m.my_life+"\t"+m.opponent_life + "\t" + m.my_center + "\t" + m.opponent_center + "\t" + m.time_span);
            }
        }

        public static void CreateHistory(ObservableCollection<HistoryViewModel> list, SavedMatch match)
        {
            list.Clear();
            if (match == null)
                return;
            for (int i = 0; i < match.savedMoments.Count; i++)
            {
                var m = match.savedMoments[i];

                list.Add(new HistoryViewModel()
                {
                    pv1 = "" + m.player1_life,
                    pv2 = "" + m.player2_life,
                    infect1 = "" + m.player1_center,
                    infect2 = "" + m.player2_center,
                    timespan = "" + m.time_span
                });

                //list.Add(new TextBlock() { Text = "" + m.player1_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Width = 70 });
                //list.Add(new TextBlock() { Text = "" + m.player1_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(75, -27, 0, 0), Width = 70 });
                //list.Add(new TextBlock() { Text = "" + m.player2_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(150, -27, 0, 0), Width = 70 });
                //list.Add(new TextBlock() { Text = "" + m.player2_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(225, -27, 0, 0), Width = 70 });
                //list.Add(new TextBlock() { Text = "" + m.time_span, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(320, -27, 0, 0), Width = 140 });

            }
        }

        private static bool user_control_change = true;
        //private static int prev_selected = -1;
        public static void SelectionChange(ListBox list)
        {
            if (list.Items.Count == 0)
                return;
            if (!user_control_change)
                return;
            user_control_change = false;

            //var index = list.SelectedIndex;
            //if (index > prev_selected)
            //{
            var last_selected = (TextBlock)list.SelectedItems[list.SelectedItems.Count - 1];
            var index = list.Items.IndexOf(last_selected);
            //}

            list.SelectedItems.Clear();

            Action<int, int> seleziona_riga = new Action<int, int>((i, offset) =>
            {
                for (int j = offset; j < 5 + offset; j++)
                    list.SelectedItems.Add(list.Items[j + i]);
            });

            seleziona_riga(index, -(index % 5));
            user_control_change = true;

            #region prove
            //if (Lista.Items.Count == 0)
            //    return;
            //if (!user_control_change)
            //    return;
            //user_control_change = false;
            //var index = Lista.SelectedIndex;

            //Lista.SelectedItems.Clear();

            //Action<int, int> seleziona_riga = new Action<int, int>((i, offset) =>
            //{
            //    for (int j = offset; j < 5 + offset; j++)
            //        Lista.SelectedItems.Add(Lista.Items[j + i]);
            //});

            //seleziona_riga(index, -(index % 5));
            //user_control_change = true;
            /*if (!user_control_change)
                return;
            user_control_change = false;
            Action<int> seleziona_indice = new Action<int>((i) =>
            {
                var a = (ListBoxItem)(Lista.Items.ElementAt(i));
                a.IsSelected = !a.IsSelected;
            });
            Action<int, int> seleziona_riga = new Action<int, int>((i, offset) =>
            {
                for (int j = offset; j < 5+offset; j++)
                    seleziona_indice(i+j);
            });
            try
            {
                var last_selected = (ListBoxItem)Lista.SelectedItems[Lista.SelectedItems.Count - 1];
                var index = Lista.Items.IndexOf(last_selected);
                bool prev_selected = last_selected.IsSelected;
                
                //if(prev_selected)
                    Lista.SelectedItem = null;
                //else
                    seleziona_riga(index, -(index % 5));
                
            }
            catch (Exception ex)
            {
                ex.ToString();
                Lista.SelectedItem = null;

            }
            finally
            {
                user_control_change = true;
            }
             */
            #endregion
        }

        public static void SaveToDisk(SavedMatch newSavedMatch)
        {
            var now = DateTime.Now.TimeOfDay;
            var h = "" + (now.Hours < 10 ? "0" : "") + now.Hours;
            var m = "" + (now.Minutes < 10 ? "0" : "") + now.Minutes;
            var s = "" + (now.Seconds < 10 ? "0" : "") + now.Seconds;
            SavedMatches savedMatches = History.LoadSavedMatches();
            newSavedMatch.name = newSavedMatch.player1_name + " vs " + newSavedMatch.player2_name + " - " +
                DateTime.Now.ToShortDateString() + " - " + h + ":" + m + ":" + s;
            if (App.isTrial())
                savedMatches.matches.Clear();
            savedMatches.matches.Add(newSavedMatch);
            SaveSavedMatches(savedMatches);
        }
        public static SavedMatches LoadSavedMatches()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamFile = appStorage.OpenFile("SavedMatches.xml", FileMode.OpenOrCreate))
                {
                    try
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(SavedMatches));
                        using (var reader = new StreamReader(streamFile))
                            return serializer.Deserialize(reader) as SavedMatches;
                    }
                    catch (Exception) { return new SavedMatches(); }
                }
            }
        }

        public static void DeleteSavedMatches()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("SavedMatches.xml");
            }
        }

        public static void SaveSavedMatches(SavedMatches state)
        {


            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("SavedMatches.xml");
                using (var streamFile = appStorage.OpenFile("SavedMatches.xml", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                //write_options_state(writer, entry);
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(SavedMatches));
                    serializer.Serialize(writer, state);
                }
            }

        }


        //public void CreateHistory()
        //{
        //    //createHTML();

        //    //webBrowser_History.Source = new Uri(Storage.GetHistoryURL(), UriKind.Relative);
        //    Lista.Items.Clear();
        //    for (int i = 0; i < match.savedMoments.Count; i++)
        //    {
        //        var m = match.savedMoments[i];
        //        Lista.Items.Add(new TextBlock() { Text = "" + m.player1_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Width = 70 });
        //        Lista.Items.Add(new TextBlock() { Text = "" + m.player1_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(75, -27, 0, 0), Width = 70 });
        //        Lista.Items.Add(new TextBlock() { Text = "" + m.player2_life, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(150, -27, 0, 0), Width = 70 });
        //        Lista.Items.Add(new TextBlock() { Text = "" + m.player2_center, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(225, -27, 0, 0), Width = 70 });
        //        Lista.Items.Add(new TextBlock() { Text = "" + m.time_span, TextAlignment = System.Windows.TextAlignment.Center, Margin = new Thickness(320, -27, 0, 0), Width = 140 });


        //        //Lista.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player1_life, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25, 0, 0, 0), Width = 70 });
        //        //Lista.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player1_center, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+75, -27, 0, 0), Width = 70 });
        //        //Lista.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player2_life, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+150, -27, 0, 0), Width = 70 });
        //        //Lista.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.player2_center, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+225, -27, 0, 0), Width = 70 });
        //        //Lista.Items.Add(new ListBoxItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Content = "" + m.time_span, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center, VerticalContentAlignment = System.Windows.VerticalAlignment.Center, Margin = new Thickness(25+320, -27, 0, 0), Width = 140 });

        //        //Lista.Items.Add("" + m.my_life+"\t"+m.opponent_life + "\t" + m.my_center + "\t" + m.opponent_center + "\t" + m.time_span);
        //    }
        //}

    }

}
